library(sasld) # 3.1 data(pesticidi) pesticidi$status <- as.character(pesticidi$status) table(pesticidi$food,pesticidi$status) Table(pesticidi$food,pesticidi$status) tbl <- table(pesticidi$food,pesticidi$status) prop.table(tbl,margin=1) # "accorcio" il nome delle modalità status <- pesticidi$status status[pesticidi$status == "Presente"] <- "Pres." status[pesticidi$status == "Assente"] <- "Ass." pesticidi$status <- status tc(pesticidi$food,pesticidi$status) # ------------------------------------------------------------------- # 3.2 data(www) internet <- www[,10] facebook <- www[,11] cor(internet,facebook) # parabola a <- -3; b <- 24; c <- 80 x <- seq(2,6,0.5) y <- a*x^2 + b*x + c cbind(x,y) cor(x,y) plot(x,y) -b/(2*a) plot(x[-c(1,2)],y[-c(1,2)],xlab="x",ylab="y") cor(x[-c(1,2)],y[-c(1,2)]) cor(x[-c(8,9)],y[-c(8,9)]) # non lineare x <- c(0,1,2,3,4,5,6) y <- c(1,2,4,8,16,32,64) cor(x,y) cor(x,log(y)) cor(x,log10(y)) # outlier set.seed(654123) x <- rnorm(50,170,10) y <- rnorm(50,170,10) cor(x,y) plot(x,y,pch=19) xx <- c(x,300); yy <- c(y,300) cor(xx,yy) plot(xx,yy,pch=19) xx <- c(x,300); yy <- c(y,10) cor(xx,yy) plot(xx,yy) # data(ballot) plot(ballot$perot,ballot$buchanan) cor(ballot$perot,ballot$buchanan) cor(ballot$perot[-50],ballot$buchanan[-50]) out <- numeric(nrow(ballot)) for (i in 1:nrow(ballot)) out[i] <- cor(ballot$perot[-i],ballot$buchanan[-i]) round(out,4) cor(ballot[,-1]) # ------------------------------------------------------------------- # 3.3 data(crime) plot(crime$college,crime$murder.rate) fit <- lm(murder.rate ~ college, data=crime) fit plot(crime$college,crime$murder.rate) abline(fit) fit.1 <- lm(murder.rate ~ college, data=crime) fit.2 <- lm(murder.rate[-9] ~ college[-9], data=crime) plot(crime$college,crime$murder.rate) abline(fit.1,lty=2,lwd=2) abline(fit.2,lty=3,lwd=2) # ------------------------------------------------------------------- # 3.4 data("flCrime") cor(flCrime$education,flCrime$crime) cor(data.frame(educ=flCrime$education,crime=flCrime$crime,urb=flCrime$ urbanization)) fit.1 <- lm(crime ~ urbanization, data=flCrime) fit.2 <- lm(education ~ urbanization, data=flCrime) cor(fit.1$residuals,fit.2$residuals) # -------------------------------------------------------------------